package com.xnx.bincker.leader.core.domain;

import com.xnx.bincker.leader.domain.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

@Configuration
public class AuditorAware implements org.springframework.data.domain.AuditorAware<String> {
	@Override
	public Optional<String> getCurrentAuditor() {
		SecurityContext securityContext = SecurityContextHolder.getContext();
		if(securityContext == null) return Optional.empty();
		Authentication authentication = securityContext.getAuthentication();
		if(authentication == null) return Optional.empty();
		Object user = authentication.getPrincipal();
		if(user instanceof User){
			return Optional.of(((User) user).getId());
		}
		return Optional.empty();
	}
}
